import { useModel } from '@umijs/max';
import React, { useEffect, useState, useRef } from 'react';
import { Layout } from 'antd';
import './module.css/module.index.css';
import { dataGet } from '@/api/index';
import EChartsComponent from '@/components/EChartsComponent';
import Slider from 'react-slick';
import nextOne from "@/assets/one.png"
import nextTwo from "@/assets/two.png"
import nextThree from "@/assets/three.png"
import nextFore from "@/assets/fore.png"
// 导入图片
import gold from '@/assets/gold.png';
import silver from '@/assets/silver.png';
import bronze from '@/assets/bronze.png';



const { Sider } = Layout;

// 改进的 ResponsiveECharts 组件，使用 ResizeObserver
const ResponsiveECharts = ({ option, style = {}, triggerResize }) => {
  const chartRef = useRef(null);
  const [containerSize, setContainerSize] = useState({ width: 0, height: 0 });
  const resizeObserverRef = useRef(null);

  useEffect(() => {
    if (!chartRef.current) return;

    const handleResize = (entries) => {
      for (let entry of entries) {
        const { width, height } = entry.contentRect;
        setContainerSize({ width, height });
      }
    };

    // 使用 ResizeObserver 监听容器大小变化
    resizeObserverRef.current = new ResizeObserver(handleResize);
    resizeObserverRef.current.observe(chartRef.current);

    return () => {
      if (resizeObserverRef.current && chartRef.current) {
        resizeObserverRef.current.unobserve(chartRef.current);
      }
    };
  }, []);

  // 当 triggerResize 变化时，手动触发一次尺寸检查
  useEffect(() => {
    if (chartRef.current) {
      const { clientWidth, clientHeight } = chartRef.current;
      setContainerSize({ width: clientWidth, height: clientHeight });
    }
  }, [triggerResize]);

  return (
    <div ref={chartRef} style={{ width: '100%', height: '100%', ...style }}>
      <EChartsComponent
        option={option}
        style={{ width: '100%', height: '100%' }}
        key={`${containerSize.width}-${containerSize.height}-${triggerResize}`}
      />
    </div>
  );
};

const Index: React.FC = () => {
  const { initialState } = useModel('@@initialState');

  // 更可靠地获取菜单折叠状态
  const isMenuCollapsed = initialState?.collapsed ?? false;
  const [responseData, setResponseData] = useState(null);
  const [studentRanking, setStudentRanking] = useState<any[]>([]);
  const [classRanking, setClassRanking] = useState<any[]>([]);
  const [excellentTeachers, setExcellentTeachers] = useState<any[]>([]);
  const [resizeTrigger, setResizeTrigger] = useState(0);
  const menuCollapsedRef = useRef(isMenuCollapsed);

  // 监听菜单折叠状态变化，使用防抖避免频繁触发
  useEffect(() => {
    // 只有当折叠状态真正改变时才触发重绘
    if (menuCollapsedRef.current !== isMenuCollapsed) {
      menuCollapsedRef.current = isMenuCollapsed;

      // 使用 setTimeout 确保在布局更新后触发重绘
      const timer = setTimeout(() => {
        setResizeTrigger(prev => prev + 1);
      }, 300); // 300ms 延迟，确保菜单动画完成

      return () => clearTimeout(timer);
    }
  }, [isMenuCollapsed]);

  // 添加窗口大小变化监听，也触发图表重绘
  useEffect(() => {
    const handleWindowResize = () => {
      setResizeTrigger(prev => prev + 1);
    };

    window.addEventListener('resize', handleWindowResize);
    return () => window.removeEventListener('resize', handleWindowResize);
  }, []);

  // 数据获取
  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await dataGet({});
        console.log(res);
        setResponseData(res);
        setStudentRanking(res.data.student_ranking || []);
        setClassRanking(res.data.squad_ranking || []);
        setExcellentTeachers(res.data.teacher || []);
      } catch (error) {
        console.error('请求出错：', error);
      }
    };
    fetchData();
  }, []);

  // 图表配置函数保持不变
  const getOrderChartOption = () => {
    if (!responseData || !responseData.data.order) return {};
    const seriesData = responseData.data.order.map((item: any) => ({
      name: item.name,
      value: item.value[0],
    }));
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      series: [
        {
          name: '订单状态',
          type: 'pie',
          radius: ['40%', '55%'],
          avoidLabelOverlap: false,
          label: {
            show: true,
            position: 'outside',
            formatter: '{d}%',
          },
          labelLine: {
            show: true,
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold',
            },
          },
          center: ['50%', '50%'],
          data: seriesData,
        },
      ],
      graphic: [
        {
          type: 'text',
          left: 'center',
          top: 'center',
          style: {
            fill: '#666',
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
      ],
    };
  };

  const getPersonChartOption = () => {
    if (!responseData || !responseData.data.person) return {};
    const seriesData = responseData.data.person.map((item: any) => ({
      name: item.name,
      value: item.value[0],
    }));
    return {
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)',
      },
      series: [
        {
          name: '人员类型',
          type: 'pie',
          radius: '50%',
          data: seriesData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
        },
      ],
    };
  };

  const getProfitChartOption = () => {
    if (!responseData || !responseData.data.TotalMoney) return {};
    return {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: '{b}: {c}'
      },
      xAxis: { type: 'value' },
      yAxis: {
        type: 'category',
        data: responseData.data.TotalMoney.label,
      },
      series: [
        {
          data: responseData.data.TotalMoney.value,
          type: 'bar',
          label: { show: false, position: 'right', fontSize: 14 },
          emphasis: { label: { show: true } },
        }
      ],
    };
  };

  const getOrderTrendOption = () => {
    if (!responseData || !responseData.data.tide) return {};
    const { xAxis: xAxisData, goods, integral } = responseData.data.tide;
    return {
      title: { text: '本月订单趋势', left: '1%', top: '1%' },
      tooltip: { trigger: 'axis' },
      legend: { data: ['商品订单', '积分订单'], bottom: '3%' },
      grid: {
        left: '5%',
        right: '5%',
        bottom: '15%',
        top: '15%',
        containLabel: true
      },
      xAxis: { type: 'category', data: xAxisData, boundaryGap: false },
      yAxis: { type: 'value' },
      series: [
        { name: '商品订单', type: 'line', data: goods, smooth: true },
        { name: '积分订单', type: 'line', data: integral, smooth: true }
      ],
    };
  };
  return (
    <>
      {/* 最上方数据统计 */}
      <div
        className='white'
        style={{ padding: '20px 0px', display: 'flex', justifyContent: 'space-around', flexWrap: 'wrap' }}
      >
        <div
          style={{
            width: '22%',
            minWidth: 200,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: '25px',
          }}
        >
          <img
            src={nextOne}
            alt="订单总收益图标"
            className='wid55'
          />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div>订单总收益</div>
            <div>
              <span style={{ color: 'black', fontSize: '28px', marginRight: '10px' }}>
                9,180.8
              </span>
              ￥
            </div>
          </div>
        </div>
        <div
          style={{ width: '1px', height: '50px', backgroundColor: '#c5c5c5ff', marginTop: '12px', display: 'none' }}
          className={isMenuCollapsed ? '' : 'show-divider'} // 根据菜单状态控制分隔线显示
        ></div>
        <div
          style={{
            width: '22%',
            minWidth: 200,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: '25px',
          }}
        >
          <img
            src={nextTwo}
            alt="今日新增订单图标"
            className='wid55'
          />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div>今日新增订单</div>
            <div>
              <span style={{ color: 'black', fontSize: '28px', marginRight: '10px' }}>1</span>个
            </div>
          </div>
        </div>
        <div
          style={{ width: '1px', height: '50px', backgroundColor: '#c5c5c5ff', marginTop: '12px', display: 'none' }}
          className={isMenuCollapsed ? '' : 'show-divider'}
        ></div>

        <div
          style={{
            width: '22%',
            minWidth: 200,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: '25px',
          }}
        >
          <img
            src={nextThree}
            alt="今日新增评论图标"
            className='wid55'
          />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div>今日新增评论</div>
            <div>
              <span style={{ color: 'black', fontSize: '28px', marginRight: '10px' }}>0</span>个
            </div>
          </div>
        </div>
        <div
          style={{ width: '1px', height: '50px', backgroundColor: '#c5c5c5ff', marginTop: '12px', display: 'none' }}
          className={isMenuCollapsed ? '' : 'show-divider'}
        ></div>

        <div
          style={{
            width: '22%',
            minWidth: 200,
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            gap: '25px',
          }}
        >
          <img
            src={nextFore}
            alt="较昨日新增图标"
            className='wid55'
          />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            <div>较昨日新增</div>
            <div>
              <span style={{ color: 'black', fontSize: '28px' }}>0.0%</span>
            </div>
          </div>
        </div>
      </div>
      <div style={{ height: '15px' }}></div>

      {/* 图表区域 */}
      <div style={{
        display: 'flex',
        gap: '20px',
        padding: '20px 0px',
        flexWrap: 'wrap',
      }}>
        {responseData && (
          <>
            <div style={{
              flex: 1,
              minWidth: 300,
              backgroundColor: 'white',
              height: '400px',
              marginBottom: '20px'
            }}>
              <div style={{ padding: '10px 0px 0px 10px' }}>订单统计</div>
              <ResponsiveECharts
                option={getOrderChartOption()}
                style={{ height: '350px' }}
                triggerResize={resizeTrigger}
              />
              <div style={{ display: 'flex', justifyContent: 'center', gap: '5px', marginTop: '-30px', flexWrap: 'wrap' }}>
                <span style={{ color: '#249EFF' }} className='size12'>
                  <span style={{ backgroundColor: '#249EFF' }} className='radiu10'></span>待付款
                </span>
                <span style={{ color: '#846BCE' }} className='size12'>
                  <span style={{ backgroundColor: '#846BCE' }} className='radiu10'></span>已付款
                </span>
                <span style={{ color: '#21CCFF' }} className='size12'>
                  <span style={{ backgroundColor: '#21CCFF' }} className='radiu10'></span>已发货
                </span>
                <span style={{ color: '#0E42D2' }} className='size12'>
                  <span style={{ backgroundColor: '#0E42D2' }} className='radiu10'></span>已完成
                </span>
                <span style={{ color: '#86DF6C' }} className='size12'>
                  <span style={{ backgroundColor: '#86DF6C' }} className='radiu10'></span>已评价
                </span>
                <span style={{ color: '#E5E6EB' }} className='size12'>
                  <span style={{ backgroundColor: '#E5E6EB' }} className='radiu10'></span>已退款
                </span>
              </div>
            </div>
            <div style={{
              flex: 1,
              minWidth: 300,
              backgroundColor: 'white',
              height: '400px',
              marginBottom: '20px'
            }}>
              <div style={{ padding: '10px 0px 0px 10px' }}>人员占比</div>
              <ResponsiveECharts
                option={getPersonChartOption()}
                style={{ height: '350px' }}
                triggerResize={resizeTrigger}
              />
              <div style={{ display: 'flex', justifyContent: 'center', gap: '10px', marginTop: '-30px' }}>
                <span style={{ color: '#249EFF' }} className='size12'>
                  <span style={{ backgroundColor: '#249EFF' }} className='radiu10'></span>教师
                </span>
                <span style={{ color: '#21CCFF' }} className='size12'>
                  <span style={{ backgroundColor: '#21CCFF' }} className='radiu10'></span>学员
                </span>
              </div>
            </div>
            <div style={{
              flex: 1,
              minWidth: 300,
              backgroundColor: 'white',
              height: '400px',
              marginBottom: '20px'
            }}>
              <div style={{ padding: '10px 0px 0px 10px' }}>收益统计</div>
              <ResponsiveECharts
                option={getProfitChartOption()}
                style={{ height: '350px' }}
                triggerResize={resizeTrigger}
              />
            </div>
          </>
        )}
      </div>

      {/* 排行榜区域 */}
      <div style={{
        display: 'flex',
        gap: '20px',
        padding: '20px 0px',
        flexWrap: 'wrap',
      }}>
        {responseData && (
          <>
            {/* 学生积分排行 */}
            <div style={{
              flex: 1,
              minWidth: 300,
              backgroundColor: 'white',
              height: '400px',
              overflowX: 'auto',
              scrollbarWidth: 'none',
              msOverflowStyle: 'none',
              marginBottom: '20px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px' }}>
                <div>学生积分排行</div>
                <a>查看更多</a>
              </div>
              <div style={{ borderCollapse: 'collapse', width: '100%' }}>
                <table style={{ width: '96%', marginLeft: '2%' }}>
                  <thead>
                    <tr style={{ backgroundColor: '#f0f0f0', height: '40px' }}>
                      <th>排名</th>
                      <th>学生</th>
                      <th>积分</th>
                    </tr>
                  </thead>
                  <tbody>
                    {studentRanking.map((item, index) => (
                      <tr key={index} style={{ borderBottom: '1px solid #eee', padding: '5px' }}>
                        <td style={{ textAlign: 'center', height: '40px' }}>
                          {index === 0 && <img src={gold} alt="金牌" style={{ width: '30px', height: '30px' }} />}
                          {index === 1 && <img src={silver} alt="银牌" style={{ width: '30px', height: '30px' }} />}
                          {index === 2 && <img src={bronze} alt="铜牌" style={{ width: '30px', height: '30px' }} />}
                          {index > 2 && index + 1}
                        </td>
                        <td style={{ width: '50%' }}>
                          <img src={item.avatar || 'https://via.placeholder.com/30'} alt={item.name} style={{ width: '30px', height: '30px', marginRight: '5px', marginLeft: '30%' }} />
                          {item.name}
                        </td>
                        <td style={{ textAlign: 'center' }}>{item.score}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* 班级积分排行 */}
            <div style={{
              flex: 1,
              minWidth: 300,
              backgroundColor: 'white',
              height: '400px',
              overflowX: 'auto',
              marginBottom: '20px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px' }}>
                <div>班级积分排行</div>
                <a>查看更多</a>
              </div>
              <div style={{ borderCollapse: 'collapse', width: '100%' }}>
                <table style={{ width: '96%', marginLeft: '2%' }}>
                  <thead>
                    <tr style={{ backgroundColor: '#f0f0f0', height: '40px' }}>
                      <th>排名</th>
                      <th>班级</th>
                      <th>积分</th>
                    </tr>
                  </thead>
                  <tbody>
                    {classRanking.map((item, index) => (
                      <tr key={index} style={{ borderBottom: '1px solid #eee', padding: '5px' }}>
                        <td style={{ textAlign: 'center', height: '40px' }}>
                          {index === 0 && <img src={gold} alt="金牌" style={{ width: '30px', height: '30px' }} />}
                          {index === 1 && <img src={silver} alt="银牌" style={{ width: '30px', height: '30px' }} />}
                          {index === 2 && <img src={bronze} alt="铜牌" style={{ width: '30px', height: '30px' }} />}
                          {index > 2 && index + 1}
                        </td>
                        <td style={{ textAlign: 'center' }}>{item.title}</td>
                        <td style={{ textAlign: 'center' }}>{item.squad_score}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            {/* 优秀教师展示 */}
            <div style={{
              flex: 1,
              minWidth: 300,
              backgroundColor: 'white',
              position: 'relative',
              height: '400px',
              marginBottom: '20px'
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '10px' }}>
                <div>优秀教师展示</div>
                <a href="#" style={{ color: 'blue' }}>查看更多</a>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', height: '90%' }}>
                <div style={{ height: '300px', width: '100%' }}>
                  {excellentTeachers.length > 0 ? (
                    <Slider
                      dots={true}
                      infinite={true}
                      speed={500}
                      slidesToShow={1}
                      slidesToScroll={1}
                      adaptiveHeight={true}
                      autoplay={true}
                      autoplaySpeed={2000}
                      dotsClass="slick-dots slick-dots-right"
                    >
                      {excellentTeachers.map((avatar, index) => (
                        <div key={index} style={{ textAlign: 'center', height: '440px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                          <img
                            src={avatar}
                            alt={`优秀教师${index + 1}`}
                            style={{
                              maxWidth: '90%',
                              borderRadius: '10px',
                              objectFit: 'cover',
                              margin: 'auto'
                            }}
                          />
                        </div>
                      ))}
                    </Slider>
                  ) : (
                    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '300px' }}>
                      暂无数据
                    </div>
                  )}
                </div>
              </div>
            </div>
          </>
        )}
      </div>

      {/* 最下方折线图 */}
      <div style={{ padding: '20px 0px' }}>
        {responseData && responseData.data.tide && (
          <div style={{ backgroundColor: 'white', height: '400px', padding: '10px', width: '100%' }}>
            <ResponsiveECharts
              option={getOrderTrendOption()}
              style={{ height: '100%', width: '100%' }}
              triggerResize={resizeTrigger}
            />
          </div>
        )}
      </div>
    </>
  );
};

export default Index;
